#include <iostream>
#include <string.h>
#include <math.h>
#include <vector>
using namespace std;

int lastStoneWeightII(vector<int>& stones) {
    int sum = 0;
    for (unsigned int i = 0; i < stones.size(); i++) sum += stones[i];
    int target = sum / 2;
    int dp[target + 1];
    memset(dp, 0, sizeof(dp));
    for (unsigned int i = 0; i < stones.size(); i++) { //先遍历物品
        for (int j = target; j >= stones[i]; j-- ) { //后倒叙遍历target容量
            dp[j] = fmax(dp[j], dp[j - stones[i]] + stones[i]);
        }
    }
    return sum - 2 * dp[target];
}

int main(){
    vector<int> stones = {2, 7, 4, 1, 8, 1};
    cout << lastStoneWeightII(stones) << endl;
    return 0;
}